package com.jacken.mars.commons.config;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wangqiang
 * @version 1.0
 * @date 2021/2/10 20:35
 */
public class SessionPool {


    public static Map<String, Session> sessions = new ConcurrentHashMap<>();


    /**
     * 关闭连接
     *
     * @param sessionId
     * @throws IOException
     */
    public static void close(String sessionId) throws IOException {
        for (String userId : SessionPool.sessions.keySet()) {
            Session session = sessions.get(userId);
            if (session.getId().equals(sessionId)) {
                sessions.remove(userId);
                break;
            }
        }

    }

    /**
     * 发送消息
     *
     * @param sessionId
     * @param message
     */
    public static void sendMessage(String sessionId, String message) {
        sessions.get(sessionId).getAsyncRemote().sendText(message);
    }


    /**
     * 群发消息
     *
     * @param message
     */
    public static void sendMessage(String message) {
        for (String userId : SessionPool.sessions.keySet()) {
            SessionPool.sessions.get(userId).getAsyncRemote().sendText(message);
        }

    }


}
